package com.kye.express.business.comment;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.databinding.ActivityCommentListBinding;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.comment.mine.CommentMineItemBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import net.yslibrary.android.keyboardvisibilityevent.util.UIUtil;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

public class CommentListActivity extends BaseAppCompatActivity implements CommentContract.CommentView {

    private ActivityCommentListBinding binding;
    private CommentContract.CommentPresenter presenter;
    private MultiTypeAdapter adapter;

    public static void startActivity(Context context) {
        Intent i = new Intent(context, CommentListActivity.class);
        context.startActivity(i);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_comment_list);
        presenter = new CommentContract.CommentPresenter();
        presenter.onCreate(savedInstanceState);
        presenter.bind(this);
        initToolbar();
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    private void initToolbar() {
        setSupportActionBar(binding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initViews(Bundle savedInstanceState) {
        adapter = new MultiTypeAdapter();
        adapter.register(CommentMineItemBean.class, new CommentMineViewBinder());
        binding.rvComments.setLayoutManager(new LinearLayoutManager(this));
        HorizontalDividerItemDecoration itemDecoration = new HorizontalDividerItemDecoration.Builder(this)
                .color(getResources().getColor(R.color.window_background))
                .size((int) UIUtil.convertDpToPx(this, 10f)).build();
        binding.rvComments.addItemDecoration(itemDecoration);
        binding.rvComments.setItemAnimator(new DefaultItemAnimator());
        binding.rvComments.setAdapter(adapter);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
//                        binding.statusLayout.showLoadingView();
                        presenter.refreshFirst();
                    }
                });
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
//                        binding.statusLayout.showLoadingView();
                        presenter.refreshFirst();
                    }
                });
        binding.llErrorServer.tvErrorServerText.setText("未登录");
        binding.llErrorServer.btErrorServerRetry.setVisibility(View.GONE);
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                    }
                });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {

            }
        });
        binding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.loadmore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.refresh();
            }
        });
    }

    private void initData(Bundle savedInstanceState) {
        binding.statusLayout.showLoadingView();
        /**
         * todo : observer user info and start init
         */
        presenter.getuserInfo();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        presenter.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public void refreshFirstSuccess(List<CommentMineItemBean> notificationList) {
        if (notificationList.size() > 0) {
            if (notificationList != null && notificationList.size() >= PageInfo.SIZE_DEFAULT) {
                binding.refreshLayout.setEnableLoadmore(false);
            }
            binding.statusLayout.showContentView();
            adapter.setItems(notificationList);
            adapter.notifyDataSetChanged();
        } else {
            binding.statusLayout.showEmptyView();
        }
    }

    @Override
    public void refreshFirstFailed(Throwable e) {
        binding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void refreshSuccess(List<CommentMineItemBean> notificationList) {
        binding.refreshLayout.finishRefresh(true);
        if (notificationList != null && notificationList.size() >= PageInfo.SIZE_DEFAULT) {
            binding.refreshLayout.setEnableLoadmore(false);
        }
        adapter.setItems(notificationList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void refreshFailed(Throwable e) {
        binding.refreshLayout.finishRefresh(false);
    }

    @Override
    public void loadMoreSuccess(List<CommentMineItemBean> notificationList) {
        binding.refreshLayout.finishLoadmore(true);
        if (notificationList != null && notificationList.size() >= PageInfo.SIZE_DEFAULT) {
            binding.refreshLayout.setEnableLoadmore(false);
        }
        List<CommentMineItemBean> datas = (List<CommentMineItemBean>) adapter.getItems();
        int startP = datas.size();
        datas.addAll(notificationList);
        adapter.notifyItemRangeInserted(startP, datas.size());
    }

    @Override
    public void loadMoreFailed(Throwable e) {
        binding.refreshLayout.finishLoadmore(false);
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public ActivityCommentListBinding getDataBinding() {
        return binding;
    }

    @Override
    public void quit() {
        finish();
    }
}
